package com.swift.client.netty;

import com.netty.client.socket.ImSocketClientHandler;
import com.netty.constant.Constants;
import com.netty.model.SentBody;
import com.netty.model.proto.SentBodyProto;
import com.swift.client.utils.IpUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

@Component
public class ImHandler implements ImSocketClientHandler {
    @Autowired
    private RestTemplate restTemplate;
    @Value("${ipUrl}")
    private String url;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        SentBodyProto.Model.Builder body = SentBodyProto.Model.newBuilder();
        body.setKey(Constants.ImserverConfig.CLIENT_CONNECT_BIND);
        body.setTimestamp(new Date().getTime());
        body.putData("uid", "asdf");
        body.putData("channel", Constants.ImserverConfig.SOCKET);
        body.putData("appVersion", "1.0");
        body.putData("osVersion", "");
        body.putData("packageName", "");
        body.putData("ip", new IpUtils(restTemplate).getIpv4(url));
        body.putData("deviceId", "");
        body.putData("deviceName", "");
        ctx.writeAndFlush(body);
    }

    @Override
    public void channelRead0(Channel channel, SentBody sentBody) {
        switch (sentBody.getKey()) {
            case "ping":
                SentBodyProto.Model.Builder message = SentBodyProto.Model.newBuilder();
                message.setKey("pong");
                message.setTimestamp(System.currentTimeMillis());
                channel.writeAndFlush(message);
                break;
            case "message":
                System.out.println(sentBody.get("body"));
                break;
        }
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) {
        System.out.println("断开链接");
    }
}
